const { Article } = require("../model");

exports.showIndex = async (req, res, next) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const pageSize = 10;
    const articles = await Article.find()
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .sort("-createdAt");
    const articlesCount = await Article.countDocuments();
    res.render("index.html", {
      articles,
      page,
      pageSize,
      articlesCount,
      totalPage: Math.ceil(articlesCount / pageSize),
    });
  } catch (error) {
    next(error);
  }
};

exports.showEditor = async (req, res) => {
  try {
    res.render("editor.html");
  } catch (error) {
    next(error);
  }
};

exports.showArticle = async (req, res) => {
  try {
    const article = await Article.findById(req.params.articleId);
    res.render("article.html", {
      article,
    });
  } catch (error) {
    next(error);
  }
};

exports.createArticle = async (req, res) => {
  try {
    const article = new Article({
      ...req.body.article,
      author: req.session.user._id,
    });
    await article.save();
    res.status(201).json({
      article,
    });
  } catch (error) {
    next(error);
  }
};
